昨天我們學了 margin collapse 和 block/inline 元素的邊界陷阱,今天我們來討論另一個前端常見的「排版魔法」:文字行距與垂直間距控制。
HTML 文字的排版,不只是字體大小和顏色,行高(line-height) 會影響閱讀體驗、元件大小以及元件內的垂直空間感。
想像文字像一列列火車,行高就是車廂之間的間距:
HTML:
<p class="text-default">
If you be lazier and get up even later, You wouldn't see such a beautiful sunrise Does it matter?
</p>
<p class="text-tight">
Tides of time rise and fall Days and nights switch and whirl The infinite loop will never come to an end.
</p>
<p class="text-loose">
I weave the gown with thorns, You shall repay with sacrifice of wounds.
</p>
CSS:
.text-default {
font-size: 16px;
line-height: 1.5; /* 1.5 倍字體大小 */
}
.text-tight {
font-size: 16px;
line-height: 1.2; /* 緊湊文字 */
}
.text-loose {
font-size: 16px;
line-height: 2; /* 鬆散文字 */
}
line-height: 1.5
→ 1.5 倍字體大小,簡單、易讀
line-height 可以寫 數字、像素(px)、百分比(%)
常用數字 → 相對字體大小,不會因不同字體大小破版
文字行高也會影響卡片、按鈕、標籤等元件的垂直空間。例如:
<button class="btn btn-primary">我是按鈕</button>
.btn {
font-size: 16px;
line-height: 1.5; /* 文字垂直置中 */
padding: 10px 20px;
}
元件高度 = padding 上下 + line-height
調整 line-height 可以讓文字垂直置中,而不用額外修改 padding
尤其適用按鈕、卡片標題、標籤、通知訊息
在卡片或列表元件中,常常要限制文字顯示行數,避免破版:
.card-title {
font-size: 18px;
line-height: 1.4;
max-height: 2.8em; /* 兩行文字 */
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* 限制 2 行 */
-webkit-box-orient: vertical;
}
-webkit-line-clamp
→ 限制顯示行數overflow: hidden
→ 超出的隱藏text-overflow: ellipsis
→ 多餘文字顯示「...」
配合 line-height → 控制每行高度
4.小技巧
把文字想成小人排隊,比如:
行高太小 → 擁擠、踩到別人腳
行高適中 → 間距舒適,大家都看得清楚
行高太大 → 空間浪費,像走廊太寬
小結:熟悉 line-height,閱讀體驗和元件美觀都能大幅提升!